package src.tree.level_order;

import src.tree.TreeNode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class no637 {//二叉树的层平均值

    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> res = new ArrayList<>();
        ArrayDeque<TreeNode> queue = new ArrayDeque<>();

        if (root == null) return res;
        queue.offer(root);
        while (!queue.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            int size = queue.size();

/*            while (size-- > 0) {
                TreeNode node = queue.poll();
                list.add(node.val);
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }

            double sum = 0;
            for (int num : list) {
                sum += num;
            }
            res.add(sum / list.size());*/

            //用for可以少一次循环求sum的过程，运行时间4ms -> 2ms
            double sum = 0;
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                //list.add(node.val);
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
                sum += node.val;
            }
            res.add(sum / size);
        }
        return res;
    }
}
